<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '提交订单',
    enablePullDownRefresh: false,
  },
}
</route>
<template>
  <view class="page">
    <view class="product" v-if="goodsList.length">
      <around :showSales="false" :data="item" nameKey="goods_name" v-for="item in goodsList" :key="item.id">
        <view class="mt-auto">
          <discount-bar :levelName="item.levelName" :price="item.member_price" />
        </view>
      </around>

      <view v-if="isShowAn" class="flex justify-center items-center text-sm mt-4 text-[#9A9A9A]"
        @click="handleToggleShowAll">
        <text>{{ state.showAll ? '收起' : '展开' }}</text>
        <wd-icon :name="state.showAll ? 'arrow-up' : 'arrow-down'" size="32rpx"></wd-icon>
      </view>
    </view>

    <view class="mt-[20rpx]">
      <view class="cell" v-for="(item, k, index) in state.buyInfo" :key="index" @click="handleCellClick(k)">
        <view class="cell-left">
          <image :src="item.icon" class="w-[32rpx] h-[32rpx] mr-[11rpx]"></image>
          <text>{{ item.name }}</text>
        </view>
        <view class="cell-right">
          <view v-if="k === 'deduction' && state.orderInfo.integral_price" class="flex items-center mr-1"
            @click.stop="handleUsedIntegral">
            <radio class="transform scale-60" color="var(--wot-color-theme)" :checked="state.usedIntegral" />
            <text class="text-[#9a9a9a]">{{ state.orderInfo.integral_price }}积分可抵扣</text>
          </view>
          <text v-if="k !== 'address'">
            <text>-￥{{ item.value }}</text>
          </text>
          <text v-else class="flex-1 ml-2 text-right">{{ item.value }}</text>
          <wd-icon name="chevron-right" size="24rpx" color="var(--wot-color-theme)"></wd-icon>
        </view>
      </view>
    </view>

    <float-bottom>
      <view class="flex items-center justify-between px-4 h-full border-t-solid border-t-1 border-[#F2F2F2]">
        <view class="text-base text-[34rpx]">
          <text class="text-[28rpx]">￥</text>
          <text class="font-bold">{{ state.orderInfo.order_amount }}</text>
        </view>

        <wd-button :round="false" :block="true" type="primary" @click="handleBuy">
          立即购买
        </wd-button>
      </view>
    </float-bottom>

    <wd-popup v-model="state.showCouponPopup" lock-scroll position="bottom" :safe-area-inset-bottom="true"
      custom-class="rounded-lg">
      <view class="px-4">
        <view class="py-4 flex justify-between items-center text-base">
          <text>选择优惠券</text>
          <wd-icon name="close" size="22rpx" color="#141719" @click="closeCouponPopup"></wd-icon>
        </view>
        <view class="max-h-[800rpx] overflow-auto">
          <coupon-list timeKey="use_time_tips" sceneKey="goods_tips" conditionKey="condition_tips" :selected="true"
            :list="state.couponList" @select="handleSelectCoupon"></coupon-list>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { fetchCreateOrder, fetchSubmitOrder, fetchPay, fetchOrderCouponList, fetchGoodsCheck } from '@/service/order'
import { to, toBack, toRedi } from '@/utils/navigation'
import { showToast, requestPayment } from '@/utils/uni'

const state = ref({
  usedIntegral: false,// 是否使用积分抵扣
  couponList: [],
  showCouponPopup: false,
  showAll: false,
  maxShow: 3,
  routeParams: {
    goods_id: '',
    source: '',
    order_id: '',
  },
  buyInfo: {
    deduction: {
      value: 0,
      name: '积分抵扣',
      icon: '/static/images/deduction.png'
    },
    discount: {
      value: 0,
      name: '商品折扣',
      icon: '/static/images/discount.png',
    },
    coupon: {
      value: 0,
      name: '优惠券',
      icon: '/static/images/coupon.png',
    },
    address: {
      value: '',
      name: '地址',
      icon: '/static/images/address.png',
    },
  },
  orderInfo: {},
})

// 是否要显示展开
const isShowAn = computed(() => {
  return state.value.orderInfo.goods.length > state.value.maxShow
})

const goodsList = computed(() => {
  if (!state.value.orderInfo?.goods) return []
  if (state.value.showAll) return state.value.orderInfo.goods
  return state.value.orderInfo.goods.filter((item, index) => index < state.value.maxShow)
})

const payWay = computed(() => {
  // return process.env.NODE_ENV === 'development' ? 1 : 2;
  return 2
})

const createOrderParams = computed(() => {
  const { source, goods_id, cart_id } = state.value.routeParams

  const params = {
    source,
    delivery_type: 1,
    order_type: 0,
  }

  if (source === 'cart') {
    params.cart_id = cart_id.split(',')
  } else {
    params.goods = [
      {
        item_id: goods_id,
        goods_num: 1,
      },
    ]
  }
  return params
})


function handleUsedIntegral() {
  const { usedIntegral } = state.value
  state.value.usedIntegral = !usedIntegral
  getOrderInfo()
}
function openCouponPopup() {
  state.value.showCouponPopup = true
}
function closeCouponPopup() {
  state.value.showCouponPopup = false
}

function getCouponList() {
  const { source, cart_id } = state.value.routeParams

  let params = {}
  if (source === 'buy_now') {
    params = {
      goods: createOrderParams.value.goods,
      source: 1,
    }
  } else {
    params = {
      cart_ids: cart_id.split(','),
      source: 2,
    }
  }


  fetchOrderCouponList(params).then((res) => {
    state.value.couponList = res.data.can_use
  })
}

function handleSelectCoupon(coupon) {
  state.value.buyInfo.coupon = {
    ...state.value.buyInfo.coupon,
    ...coupon,
    value: coupon.money,
  }
  closeCouponPopup()
  getOrderInfo()
}

function orderCheck(params, callback) {
  fetchSubmitOrder({ ...params, is_check: 1 }).then((res) => {
    if (typeof callback === "function") {
      callback(res);
    }
  });
}

function handleBuy() {
  const { address, coupon } = state.value.buyInfo
  if (!address?.id) {
    showToast('请选择地址')
    return
  }
  uni.showLoading({
    mask: true,
  })

  const params = {
    ...createOrderParams.value,
    action: 'buy',
    address: address.id,
    coupon_list_id: coupon.id || 0,
    is_integral: Number(state.value.usedIntegral),
  }

  let orderId;

  orderCheck(params, async () => {
    try {
      const res = await fetchSubmitOrder(params)
      const { order_id } = res.data;
      orderId = order_id;
      const result = await fetchPay({
        order_id,
        pay_way: payWay.value,
        from: 'order',
        order_source: 3,
      })

      if (payWay.value == 1 || result.data.is_pay) {
        showToast('支付成功', toBack)
      } else {
        await requestPayment(result.data.config)
        showToast('支付成功', toBack)
      }
    } catch (err) {
      console.error(err)
      if (coupon.id) {
        state.value.buyInfo.coupon = {
          ...state.value.buyInfo.coupon,
          value: 0,
          id: 0,
        }
      }
      getCouponList()
      showToast('支付失败', () => {
        toRedi(`pages-sub/person/order-detail?id=${orderId}`)
      })
    } finally {
      uni.hideLoading()
    }
  })

}
function handleCellClick(key) {
  switch (key) {
    case 'address': {
      to(`pages-sub/person/address?used=1`)
      break
    }
    case 'coupon': {
      openCouponPopup()
      break
    }
    case 'deduction': {
      if (!state.value.orderInfo.integral_price) showToast('暂无积分可抵扣')
      break
    }
  }
}

function fomatAddress(address) {
  const { province, city, district } = address
  const addressValue = district ? `${province}${city}${district}${address?.address}` : ''
  state.value.buyInfo.address = {
    ...state.value.buyInfo.address,
    ...address,
    value: addressValue,
  }
}

function getOrderInfo() {
  uni.showLoading({
    title: '加载中',
    mask: true,
  })

  fetchCreateOrder({
    ...createOrderParams.value,
    is_integral: Number(state.value.usedIntegral),
    action: 'settle',
    coupon_list_id: state.value.buyInfo.coupon.id || 0,
  })
    .then((res) => {
      const { address, member_amount, integral_amount } = res.data
      state.value.orderInfo = res.data
      state.value.buyInfo.discount.value = member_amount
      state.value.buyInfo.deduction.value = integral_amount
      fomatAddress(address)
    })
    .finally(uni.hideLoading)
}

function handleToggleShowAll() {
  state.value.showAll = !state.value.showAll
}

onLoad((params) => {
  state.value.routeParams = params
  getOrderInfo()
  getCouponList()
  uni.$on('usedAddress', fomatAddress)
})

onUnload(() => {
  uni.$off('usedAddress', fomatAddress)
})
</script>

<style lang="scss" scoped>
.page {
  @include addSafeArea(146rpx);
}

.product {
  @apply px-4 pt-5 pb-4;
  box-shadow: 0rpx 3rpx 10rpx 1rpx rgba(0, 0, 0, 0.1);
}

.cell {
  @apply p-4 flex justify-between items-center text-sm;
  border-bottom: 1px solid #ededed;

  &-left {
    @apply flex items-center;
    color: #9a9a9a;
  }

  &-right {
    @apply flex items-center text-base flex-1 justify-end flex-wrap;
  }
}
</style>
